/**
 * Copyright (C), 2015-2020, XXX有限公司
 * FileName: LifeFragment
 * Author: Clark
 * Date: 2020/10/7 18:46
 * Description:
 * History:
 * <author> <time> <version> <desc>
 * 作者姓名 修改时间 版本号 描述
 */
package sz.szsmk.citizencard.ui.fragment;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebViewClient;
import android.widget.Toast;

import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.gyf.immersionbar.ImmersionBar;
import com.umeng.commonsdk.debug.E;

import java.util.ArrayList;
import java.util.List;

import sz.szsmk.citizencard.DaggerApplication;
import sz.szsmk.citizencard.R;
import sz.szsmk.citizencard.databinding.FragmentLifeMainBinding;
import sz.szsmk.citizencard.gover.FunctionItem;
import sz.szsmk.citizencard.ioc.Compontent.DaggerCommonFragmentComponent;
import sz.szsmk.citizencard.model.network.bean.response.GetOrderOpenidRes;
import sz.szsmk.citizencard.model.network.bean.response.PrepayResponse;
import sz.szsmk.citizencard.model.network.bean.response.ServiceTypeRes;
import sz.szsmk.citizencard.mvp.contract.IAppLifeContact;
import sz.szsmk.citizencard.mvp.presenter.LifePresenter;
import sz.szsmk.citizencard.ui.activity.IMainActivity;
import sz.szsmk.citizencard.ui.adapter.AllTypeAdapter;
import sz.szsmk.citizencard.ui.base.IBaseFragment;
import sz.szsmk.citizencard.util.ACache;
import sz.szsmk.citizencard.util.Constant;
import sz.szsmk.citizencard.util.JumpUtils;
import sz.szsmk.citizencard.util.StringUtils;
import sz.szsmk.citizencard.widget.MyLinearLayout;
import sz.szsmk.citizencard.widget.lifeweb.JSInterface;
import sz.szsmk.citizencard.widget.lifeweb.LifeWebView;
import sz.szsmk.citizencard.widget.lifeweb.LifeWebViewClient;

/**
 * @ClassName: LifeFragment
 * @Description:
 * @Author: Clark
 * @Date: 2020/10/7 18:46
 */
public class LifeFragment extends IBaseFragment<LifePresenter, FragmentLifeMainBinding> implements IAppLifeContact.IAppLifeView, LifeWebViewClient.hideTitleBar, LifeWebViewClient.RestorePosition {
    private LifeWebView lifeWebView;
    AllTypeAdapter allTypeAdapter;
    private ArrayList<PrepayResponse.WebsiteListInfoBean> websiteListInfo = new ArrayList<>();
    private ArrayList<PrepayResponse.WebsiteListInfoBean> allInfoList = new ArrayList<>();
    private String HUIMINExtend = "";
    String access_token;
    Bundle savedState;
    int lifeScrollViewPosition = 0;
    int finalPosition = 0;

    public static LifeFragment getInstance() {
        LifeFragment lifeFragment = new LifeFragment();
        return lifeFragment;
    }

    @Override
    protected int attachLayoutRes() {
        return R.layout.fragment_life_main;
    }

    @Override
    protected void initInjector() {
        DaggerCommonFragmentComponent.builder().appCompontent(DaggerApplication.getAppComponent())
                .build().inject(this);
    }

    @Override
    protected void initViews() {
        initWebView();//没有调用获取orderId的方法
        dataBinding.backLayout.settingTitle.setText("生活");
        dataBinding.backLayout.back.setVisibility(View.GONE);

        //MainActivity沉浸  手动改变view的高度  便于 滑动整体 标题栏变色
        ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) dataBinding.backLayout.vStatusBar.getLayoutParams();
        layoutParams.height = ImmersionBar.getStatusBarHeight(requireActivity());
        dataBinding.backLayout.vStatusBar.setLayoutParams(layoutParams);
        dataBinding.backLayout.vStatusBar.setBackgroundColor(ContextCompat.getColor(requireContext(),R.color.color_2184FA));

        allTypeAdapter = new AllTypeAdapter(getActivity(),"life");
        dataBinding.lifeContent.setLayoutManager(new LinearLayoutManager(getActivity()));
        dataBinding.lifeContent.setAdapter(allTypeAdapter);
        //{"distance_type":"0","latitude":"31.342804","longitude":"120.621852","page_num":"1","page_size":"15","service_type":"0","site_type":"0"}

        dataBinding.lifeSiteMore.setOnClickListener(v->{
            JumpUtils.jump(mContext, "nerwork", 1);
        });


    }

    @Override
    protected void updateViews() {
    }


    private void initWebView() {
//         access_token = ACache.get(getActivity()).getAsString("access_token");
        lifeWebView = dataBinding.webView;
        lifeWebView.setVerticalScrollBarEnabled(true);
        lifeWebView.setHorizontalScrollBarEnabled(false);
        lifeWebView.getSettings().setSupportZoom(true);
        lifeWebView.getSettings().setBuiltInZoomControls(true);
        lifeWebView.getSettings().setJavaScriptEnabled(true);
        lifeWebView.getSettings().setDomStorageEnabled(true);
//        lifeWebView.getSettings().setPluginsEnabled(true);/
        lifeWebView.requestFocus();
        lifeWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        lifeWebView.getSettings().setUseWideViewPort(true);
        lifeWebView.getSettings().setLoadWithOverviewMode(true);
        lifeWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
//        lifeWebView.loadUrl("http://zhszyfb2020.szsmk.com/app-front-end/#/live/main");
        lifeWebView.setWebViewClient(new LifeWebViewClient(getActivity(), this, this));
        lifeWebView.addJavascriptInterface(JSInterface.getInstance(getActivity()), "android");
        webViewScroolChangeListener();


        dataBinding.lifeScroll.setOnScrollChangeListener(new View.OnScrollChangeListener() {
            @Override
            public void onScrollChange(View view, int i, int i1, int i2, int i3) {
//                Log.d("clark", i + "-" + i1 + "-" + i2 + "-" + i3);
                lifeScrollViewPosition = i1;
            }
        });
    }

    private void webViewScroolChangeListener() {
        lifeWebView.setOnCustomScroolChangeListener(new LifeWebView.ScrollInterface() {
            @Override
            public void onSChanged(int l, int t, int oldl, int oldt) {
                //WebView的总高度
                float webViewContentHeight = lifeWebView.getContentHeight() * lifeWebView.getScale();
                //WebView的现高度
                float webViewCurrentHeight = (lifeWebView.getHeight() + lifeWebView.getScrollY());
//                System.out.println("webViewContentHeight=" + webViewContentHeight);
//                System.out.println("webViewCurrentHeight=" + webViewCurrentHeight);
                if ((webViewContentHeight - webViewCurrentHeight) == 0) {
                    System.out.println("WebView滑动到了底端");
                }
            }
        });

    }

    @Override
    public void getWebsiteListSucc(List<PrepayResponse.WebsiteListInfoBean> websiteListInfo) {
        this.websiteListInfo.addAll(websiteListInfo);
        allTypeAdapter.setTypeData( this.websiteListInfo,0);//0的话是刷新，1是增加

    }

    @Override
    public void getWebsiteListFail() {
        Toast.makeText(mActivity, "获取数据失败", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void getGetOrderIdFail() {

    }

    @Override
    public void getGetOrderIdSucc(GetOrderOpenidRes response, String type, String url, FunctionItem data) {


    }

    @Override
    public void HideTitleBar(String code, String message) {
        try {
            if ("hide".equals(code)) {
                dataBinding.backLayout.vStatusBar.setBackgroundColor(getActivity().getResources().getColor(R.color.white));
                dataBinding.lifeContent.setVisibility(View.GONE);
                dataBinding.backLayout.toolbar.setVisibility(View.GONE);
                dataBinding.serviceSiteLabel.setVisibility(View.GONE);
                ImmersionBar.with(this)
                        .statusBarDarkFont(true, 0f)
                        .init();
            } else {
                dataBinding.backLayout.vStatusBar.setBackgroundColor(getActivity().getResources().getColor(R.color.color_2184FA));
                dataBinding.lifeContent.setVisibility(View.VISIBLE);
                dataBinding.backLayout.toolbar.setVisibility(View.VISIBLE);
                dataBinding.serviceSiteLabel.setVisibility(View.VISIBLE);
                ImmersionBar.with(this)
                        .statusBarDarkFont(false, 0f)
                        .init();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        savedState = new Bundle();
        Log.d("clark", "life on create");
    }

    @Override
    public void onPause() {
        super.onPause();
        Log.d("clark", "life onpause" + lifeScrollViewPosition);
        saveStateToArguments(lifeScrollViewPosition);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        Log.d("clark", "life onsaveInstanceState" + lifeScrollViewPosition);
        super.onSaveInstanceState(outState);
        saveStateToArguments(lifeScrollViewPosition);
    }

    @Override
    public void onResume() {
        super.onResume();
        dataBinding.lifeContent.setVisibility(View.GONE);
        dataBinding.serviceSiteLabel.setVisibility(View.GONE);
        access_token = ACache.get(getActivity()).getAsString("access_token");
        lifeWebView.loadUrl(Constant.BASE_URL + "app-front-end/#/live/main" + "?access_token=" + access_token);
        Log.d("clark", "life onResume");
        if (!restoreStateFromArguments()) {
            //第一次启动的时候进行的操作
        }
    }

    private void saveStateToArguments(int position) {
        savedState = saveState(position);
        if (savedState != null) {
            Bundle b = getArguments();
            b.putBundle("lifeFragmentPosition", savedState);
        }
    }

    private boolean restoreStateFromArguments() {
        Bundle b = getArguments();
        savedState = b.getBundle("lifeFragmentPosition");
        if (savedState != null) {
            restoreState();
            return true;
        }
        return false;
    }

    //保存数据的方法
    private Bundle saveState(int i) {
        Bundle state = new Bundle();
        state.putInt("position", i);
        return state;
    }

    //取出数据的方法
    private void restoreState() {
        if (savedState != null) {
            int position = savedState.getInt("position");
            Log.d("clark", position + "");
            if (StringUtils.isEmpty(position + "")) {
                position = 0;
            }
            finalPosition = position;
        }
    }

    @Override
    public void restorePos() {
        if (getActivity() == null) {
            return;
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(100);
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            dataBinding.lifeScroll.scrollTo(0, finalPosition);
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }
}